package com.xxh.blog.config;


import cn.hutool.core.map.MapUtil;
import com.xxh.blog.shiro.AccountRealm;
import com.xxh.blog.shiro.auFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
@Slf4j
public class ShiroConfig {

    @Bean
    public SecurityManager securityManager(AccountRealm accountRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(accountRealm);
        return securityManager;
    }

    /**
     * 配置蟹肉的拦截器
     *
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        //配置登录的url和登录成功的url以及验证失败的url
        filterFactoryBean.setLoginUrl("/login");
        filterFactoryBean.setSuccessUrl("/index");
        filterFactoryBean.setUnauthorizedUrl("/login");

        //自定义过滤器
        filterFactoryBean.setFilters(MapUtil.of("auth",auFilter()));
        //配置访问权限
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/reg", "anon");
        filterChainDefinitionMap.put("/", "anon");
        //需要认证才能访问
        filterChainDefinitionMap.put("/user/home", "authc");
        filterChainDefinitionMap.put("/user/set", "authc");
        filterChainDefinitionMap.put("/user/index", "authc");
        filterChainDefinitionMap.put("/user/message", "authc");

        filterChainDefinitionMap.put("/collection/find","authc");
        filterChainDefinitionMap.put("/collection/add","auth");
        filterChainDefinitionMap.put("/collection/remove","auth");
        //设置过滤器
        filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return filterFactoryBean;
    }

    @Bean
    public auFilter auFilter(){
        return new auFilter();
    }
}
